#include <iostream>
#include <string>
#include <signal.h>
#include <httplib.h>
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "oj_controller.hpp"

using namespace httplib;
using namespace NS_Util;
using namespace NS_Log;
using namespace NS_Controller;

static Controller* p_ctrl = nullptr;

void Recovery(int sigal)
{
    p_ctrl->RecoveryServers();
}

int main()
{
    signal(SIGQUIT, Recovery);
    // 服务路由功能
    Server svr;
    Controller ctrl;
    p_ctrl = &ctrl;

    /* 获取题库列表 */
    svr.Get("/all_questions", [&ctrl](const Request& req, Response& rsp)
        {
            std::string html;
            ctrl.GetAllQuestionsHtml(&html);

            rsp.set_content(html, "text/html; charset=utf-8");
        }
    );

    /* 根据题号获取题目内容 */
    // /questions/10 正则表达式匹配
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request& req, Response& rsp)
        {
            std::string question_number = req.matches[1];
            std::string html;
            ctrl.GetOneQuestionHtml(question_number, &html);

            rsp.set_content(html, "text/html; charset=utf-8");
        }
    );

    /* 提交代码，使用编译运行服务 */
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request& req, Response& rsp)
        {
            std::string number = req.matches[1];
            std::string res_json;
            ctrl.Judge(number, req.body, &res_json);

            rsp.set_content(res_json, "application/json; charset=utf-8");
        }
    );

    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);

    return 0;
}
